package vn.hanelsoft.openwifi.model.entity;

import java.util.ArrayList;

import vn.hanelsoft.openwifi.model.handler.DatabaseHandler;
import vn.hanelsoft.openwifi.model.object.BaseObject;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

public abstract class EntityBase {
	public DatabaseHandler _dbhandler;
	protected SQLiteDatabase _db;
	protected Context _context;
	protected String _tblname;

	public EntityBase(String tblName, Context mContext) {
		this._tblname = tblName;
		this._dbhandler = new DatabaseHandler(mContext);
		this._context = mContext;
	}

	public abstract long add(BaseObject obj);

	/**
	 * insert ban ghi vao CSDL
	 * 
	 * @param values
	 * @return id cua ban ghi moi duoc them (-1 neu ko them duoc)
	 */
	public long add(ContentValues values) {
		long id = -1;
		try {
			if (null != _db)
				_db = null;
			_db = _dbhandler.getWritableDatabase();
			id = _db.insert(_tblname, null, values);
			_db.close();
			return id;
		} catch (Exception e) {
			return id;
		}
	}

	public abstract boolean update(BaseObject obj);

	/**
	 * update ban ghi
	 * 
	 * @param values
	 * @param where
	 * @return
	 */
	public boolean update(ContentValues values, String where, String[] whereArgs) {
		try {
			if (null != _db)
				_db = null;
			_db = _dbhandler.getWritableDatabase();
			_db.update(_tblname, values, where, whereArgs);
			_db.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public abstract int delete(BaseObject obj);

	/**
	 * xoa ban ghi trong co so du lieu
	 * 
	 * @param where
	 *            : dieu kien xoa
	 * @return so ban ghi da xoa (0 neu ko xoa duoc)
	 */
	public int delete(String where, String[] whereArgs) {
		int count = 0;
		// try {
		if (null != _db)
			_db = null;
		_db = _dbhandler.getWritableDatabase();
		count = _db.delete(_tblname, where, whereArgs);
		_db.close();
		return count;
		// } catch (Exception e) {
		// return count;
		// }
	}

	public abstract BaseObject getById(String id);

	public abstract ArrayList<BaseObject> getAll();

	public ArrayList<BaseObject> search() {
		return new ArrayList<BaseObject>();
	}
}